/**
 * Copyright (c) 2018 qar All rights reserved.
 * <p>
 * https://www.qar.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.qar.cloud;

import io.minio.*;

import io.minio.errors.*;
import io.minio.http.Method;
import io.qar.commons.tools.exception.RenException;
import io.qar.exception.ModuleErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

/**
 * MinIO 存储
 *
 * @author Mark sunlightcs@gmail.com
 */

@Slf4j
public class MinioCloudStorageService extends AbstractCloudStorageService {
    private MinioClient minioClient;

    public MinioCloudStorageService(CloudStorageConfig config) {
        this.config = config;
        //初始化
        init();
    }

    private void init() {
        minioClient = MinioClient.builder().endpoint(config.getMinioEndPoint())
                .credentials(config.getMinioAccessKey(), config.getMinioSecretKey()).build();
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            // todo mm minio上传文件时，需要指定contentType
            //如果BucketName不存在，则创建
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(config.getMinioBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(config.getMinioBucketName()).build());
            }

            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(config.getMinioBucketName())
                            .object(path)
                            .stream(inputStream, inputStream.available(), -1)
                            .build()
            );

        } catch (Exception e) {
            throw new RenException(ModuleErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }
        return presignedObjectUrl(path);
    }

    /**
     * 返回签名view路径
     * @param path
     * @return
     */
    public String presignedObjectUrl(String path) {
        // 参数校验
        if (path == null || path.trim().isEmpty()) {
            log.error("Invalid path parameter.");
            throw new IllegalArgumentException("Path cannot be null or empty");
        }

        GetPresignedObjectUrlArgs args;
        try {
            // 使用建造者模式来构建GetPresignedObjectUrlArgs对象，提高灵活性
            args = GetPresignedObjectUrlArgs.builder()
                    .bucket(config.getMinioBucketName())
                    .object(path)
                    .expiry(5, TimeUnit.HOURS)
                    .method(Method.GET).build();
        } catch (Exception e) {
            log.error("Failed to build GetPresignedObjectUrlArgs", e);
            throw new RenException(ModuleErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }

        String presignedObjectUrl = null;
        try {
            presignedObjectUrl = minioClient.getPresignedObjectUrl(args);
        } catch (Exception e) {
            log.error("Failed to generate presigned object URL", e);
            throw new RenException(ModuleErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        } finally {
            return presignedObjectUrl;
        }
    }


    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getMinioPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getMinioPrefix(), suffix));
    }
}
